const { Op } = require('sequelize')

const Cart = require('../model/cart.model')
const Goods = require('../model/goods.model')

class CartService {
  async createOrUpdate(user_id, goods_id) {
    // 根据user_id和goods_id同时(Op.and)去查找，有没有记录
    let res = await Cart.findOne({
      where: { [Op.and]: { user_id, goods_id } },
    })
    if (res) {
      // 已经存在一条记录，number+1
      await res.increment('number') //自增1
      return await res.reload() // 更新记录
    } else {
      // 不存在记录，新增
      return await Cart.create({ user_id, goods_id })
    }
  }

  async findCarts(pageNum, pageSize, user_id) {
    const offset = (pageNum - 1) * pageSize

    const { count, rows } = await Cart.findAndCountAll({
      attributes: ['id', 'number', 'selected'], // SELECT `id`, `number`, `selected`
      where: { user_id },
      offset,
      limit: pageSize * 1,
      include: {
        model: Goods,
        as: 'goods_info',
        attributes: ['id', 'goods_name', 'goods_price', 'goods_img'],
      }, // 关联表查询，根据goods_id和good表里的id联合
    })

    return {
      pageNum,
      pageSize,
      total: count,
      list: rows,
    }
  }

  async updateCarts({ id, number, selected }) {
    const res = await Cart.findByPk(id) // 使用提供的主键从表中仅获得一个条目
    if (!res) return ''
    number !== undefined ? (res.number = number) : ''
    selected !== undefined ? (res.selected = selected) : ''
    return await res.save() //更新数据库
  }

  async removeCarts(ids) {
    return await Cart.destroy({
      where: {
        id: {
          [Op.in]: ids, // id in (1,2..)
        },
      },
    })
  }

  async selectAllCarts(user_id) {
    return await Cart.update({ selected: true }, { where: { user_id } })
  }

  async unselectAllCarts(user_id) {
    return await Cart.update({ selected: false }, { where: { user_id } })
  }

  async countCarts(user_id) {
    const count = await Cart.count({ where: { user_id } })
    return {
      total: count,
    }
  }
}

module.exports = new CartService()
